package com.gaojinqi.apigateway.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Objects;

public class JsonUtil {

    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 转换为json字符串
     *
     * @param object
     * @return
     */
    public static String toJson(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T fromJson(String json, Class<T> valueType) {
        Objects.requireNonNull(json, "json is null.");
        Objects.requireNonNull(valueType, "value type is null.");

        try {
            return objectMapper.readValue(json, valueType);
        } catch (IOException e) {
            throw new IllegalStateException("fail to convert [" + json + "] to [" + valueType + "].", e);
        }
    }

    public static <T> T fromJson(String json, TypeReference<T> typeReference) {
        Objects.requireNonNull(json, "json is null.");
        Objects.requireNonNull(typeReference, "typeReference type is null.");

        try {
            return objectMapper.readValue(json, typeReference);
        } catch (IOException e) {
            throw new IllegalStateException("fail to convert [" + json + "] to [" + typeReference.getType() + "].", e);
        }
    }

}
